<?php
namespace app\common;

use think\Config;

// 关于文件函数
class Files {

	public static function getSize($filesize) {
		if($filesize >= 1073741824) {
			$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
		} elseif($filesize >= 1048576) {
			$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
		} elseif($filesize >= 1024) {
			$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
		} else {
			$filesize = $filesize . ' 字节';
		}
		return $filesize;
	}

    public static function writefile($data, $file='') {
        $date = date('YmdH');

        $dir = iconv("UTF-8", "GBK", LOG_PATH.$date);
        if (!file_exists($dir)) mkdir ($dir,0777,true);

        $file = empty($file) ? $date.rand(100, 999).'.log' : $file;
        $filepath = LOG_PATH.$date.'/'.$file;
        file_put_contents($filepath, date('Y-m-d H:i:s').'-------'.json_encode($data).PHP_EOL, FILE_APPEND | LOCK_EX);
        return 1;
    }

    public static function download($path_name, $save_name)
    {
        $path_name = $path_name.$save_name;
        ob_end_clean();
        $hfile = fopen($path_name, "rb") or die("Can not find file: $path_name\n");
        Header("Content-type: application/octet-stream");
        Header("Content-Transfer-Encoding: binary");
        Header("Accept-Ranges: bytes");
        Header("Content-Length: ".filesize($path_name));
        Header("Content-Disposition: attachment; filename=\"$save_name\"");
        while (!feof($hfile)) {
            echo fread($hfile, 32768);
        }
        fclose($hfile);
    }


    public static function download_test($file_dir="",$file_name="")
    {
        if (!file_exists($file_dir . $file_name)) {
            header('HTTP/1.1 404 NOT FOUND');
        } else {
            //以只读和二进制模式打开文件
            $file = fopen($file_dir . $file_name, "rb");
            //告诉浏览器这是一个文件流格式的文件
            Header("Content-type: application/octet-stream");
            //请求范围的度量单位
            Header("Accept-Ranges: bytes");
            //Content-Length是指定包含于请求或响应中数据的字节长度
            Header("Accept-Length: " . filesize($file_dir . $file_name));
            //用来告诉浏览器，文件是可以当做附件被下载，下载后的文件名称为$file_name该变量的值。
            Header("Content-Disposition: attachment; filename=" . $file_name);
            //读取文件内容并直接输出到浏览器
            echo fread($file, filesize($file_dir . $file_name));
            fclose($file);
            exit ();
        }
    }


    public function buildHtml($htmlfile = '', $htmlpath = '', $templateFile = '')
    {
        $content = $this->fetch($templateFile);
        $htmlpath = !empty($htmlpath) ? $htmlpath : HTML_PATH;
        $htmlfile = $htmlpath . $htmlfile;
        // 如果静态目录不存在 则创建
        if (!is_dir(dirname($htmlfile))){
            mkdir(dirname($htmlfile));
        }
//        dump($htmlfile);
        @unlink($htmlfile);
        file_put_contents($htmlfile,$content);
        return $content;
    }

}

